package gaery.utils;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;

import org.apache.commons.io.FileUtils;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Path;
import org.codehaus.groovy.ant.Groovyc;

public class SourceCodeWatcher extends DirWatcher {

	String destDir = "./target/war/WEB-INF/classes/";
	
	public static void main(String[] args) throws Exception {
		System.out.println("Starting scanner on " + new File(".").getCanonicalPath());
		SourceCodeWatcher watcher = new SourceCodeWatcher();
		
		Timer timer = new Timer();
	    timer.schedule(watcher,new Date(),1000);
	}
	
	public SourceCodeWatcher() {
		super(".","groovy,gsp");
	}

	@Override
	protected void onChange(File file, String action) {
		File fDestDir = new File(destDir);
		File baseDir = new File(".");

		if (!fDestDir.isDirectory())
			throw new IllegalArgumentException("Is not a directory: " + fDestDir.getAbsolutePath());
		
		System.out.println("Changed detected for " + file.getAbsolutePath());
		
		if (file.getName().endsWith("groovy")) {
			compile(fDestDir, baseDir);
		} else {
			System.out.println("Copying gsp " + file.getAbsolutePath());
			try {
				FileUtils.copyFileToDirectory(file, new File(baseDir,"target/war/"));
			} catch (IOException e) {
				throw new RuntimeException(e.getMessage(),e);
			}
		}
	}

	private void compile(File fDestDir, File baseDir) {
		Project project = new Project();
		
		project.setBaseDir(baseDir);
		
		Groovyc groovyc = new Groovyc();
	
		groovyc.setProject(project);
		groovyc.setSrcdir(new Path(project,"."));
		groovyc.setSourcepath(new Path(project,"."));
		groovyc.setDestdir(fDestDir);
		groovyc.execute();
		System.out.println("Recompilled all to " + fDestDir.getAbsolutePath());
	}

}
